package com.itwn.portal.web;

import com.itwn.portal.entity.User;
import com.itwn.portal.reult.ResponseResult;
import com.itwn.portal.service.UserService;

import com.itwn.portal.vo.PasswordVo;
import com.itwn.portal.vo.UserRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itwn.portal.vo.BookcaseVo;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("user")
@SessionAttributes(value = {"loginUser"})
public class UserController {

    @Autowired
    UserService userService;

    /**
     * @param username
     * @param password
     * @param map
     * @return 用户的登录功能
     */
    @RequestMapping("/login")
    public String login(String username, String password, Map map, HttpServletRequest httpServletRequest) {
        User user = userService.queryUserByName(username);
        if (user == null) {
            map.put("errorInfo", "抱歉,你还没注册过,请先注册");
            return "login";
        } else {
            if (user.getStatus() == 1){
                if (user.getPassword().equals(password)) {
                    HttpSession session = httpServletRequest.getSession();
                    session.setAttribute("loginUser",user);
                    return "redirect:/index";
                } else {
                    map.put("errorInfo", "密码错误,请确认后重试");
                    return "login";
                }
            }else {
                map.put("errorInfo" , "账户违规已经被冻结,请联系管理员");
                return "login";
            }
        }
    }

    /**
     * @param user
     * @param map
     * @return 用户注册
     */
    @PostMapping("/register")
    public String registerUser(User user, String confirmPassword, Map map) {
        try {
            if (user.getPassword().equals(confirmPassword)){
                int resInt = userService.userRegister(user, confirmPassword);
                if (resInt == 1) {
                    return "index";
                } else {
                    map.put("errorInfo", "用户名已存在，不能重复注册");
                    return "login";
                }
            }else {
                map.put("errorInfo" , "两次密码不相同,请重新注册");
                return "login";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "login";
        }
    }

    @RequestMapping("/getRecord")
    @ResponseBody
    public ResponseResult<List<UserRecordVo>> queryPersonRecord(Integer uid){
        ResponseResult<List<UserRecordVo>> result = new ResponseResult<>();
        try {
            List<UserRecordVo> list = userService.queryPersonRecord(uid);
            result.setMsg("查询成功!");
            result.setCode(200);
            result.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("查询失败!");
            result.setCode(201);
        }
        return result;
    };


    @ResponseBody
    @GetMapping("/bookcase")
    public List<BookcaseVo> bookcase(Integer id){
        List<BookcaseVo> list=userService.queryBookCase(id);
        return list;

    }

    @ResponseBody
    @RequestMapping("/getLoginUser")
    public ResponseResult<Object> getLoginUser(HttpServletRequest request){
        ResponseResult<Object> result = new ResponseResult<>();
        HttpSession session = request.getSession();
        // 获取session中所有的键值
       Object object = session.getAttribute("loginUser");
        System.out.println(object+"-------------------------------------------");
        if(object!=null){
            result.setMsg("已经登录");
            result.setCode(200);
            result.setData(object);
        }else{
            result.setCode(201);
            result.setMsg("还未登录");
        }
        return result;
    }

    /**
     *
     * @param session
     * @return
     *  登出
     */
    @ResponseBody
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        try {
            session.invalidate();
        }catch (Exception e){
            e.printStackTrace();
            return "201";
        }
        return "200";
    }
    @RequestMapping("/modifyUserInfo")
    @ResponseBody
    public ResponseResult<Void> modify(@RequestBody User user){
        ResponseResult<Void> result = new ResponseResult<>();
        try{
            userService.modifyUserInfo(user);
            result.setCode(200);
            result.setMsg("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("修改失败");
        }
        return result;
    }
    @RequestMapping("/modifyPassword")
    @ResponseBody
    public ResponseResult<Void> modifyPassword(@RequestBody PasswordVo passwordVo){
        ResponseResult<Void> result = new ResponseResult<>();
        System.out.println(passwordVo);
        try{
            User user = userService.searchById(passwordVo.getId());
            if (user.getPassword().equals(passwordVo.getInitPass())){
                if(passwordVo.getNewPass().equals(passwordVo.getAgainNewPass())){
                    userService.modifyPassword(passwordVo);
                    result.setCode(200);
                    result.setMsg("修改成功");
                }else {
                    result.setCode(201);
                    result.setMsg("修改失败");
                }
            }else {
                result.setCode(201);
                result.setMsg("修改失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(201);
            result.setMsg("修改失败");
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/uploadImg")
    public ResponseResult<String> uploadImg(MultipartFile multipartFile){
        ResponseResult<String> result = new ResponseResult<>();
        try {
            String fileName= UUID.randomUUID().toString()+".jpg";
            String filePath="D:/Imgs/headImg/"+fileName;
            System.out.println(filePath);
            File file=new File(filePath);
            multipartFile.transferTo(file);
            result.setCode(200);
            result.setData(fileName);
            result.setMsg("图片添加成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("添加失败");
            result.setCode(201);
        }
        return result;
    }
    @ResponseBody
    @RequestMapping("/updateAvatar")
    public ResponseResult<Void> uploadAvatar(Integer uid,String avatar){
        ResponseResult<Void> result = new ResponseResult<>();
        try {
            userService.uploadAvatar(uid,avatar);
            result.setCode(200);
            result.setMsg("头像修改成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("头像修改失败");
            result.setCode(201);
        }
        return result;
    }
}


